package com.noreply.springlearning.async;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
// 必须要有
@EnableAsync
@ComponentScan(basePackages = {"com.noreply.springlearning.async"})
public class ThreadPoolTaskConfig {
/**
 * 默认情况下，在创建了线程池后，线程池中的线程数为0，当有任务来之后，就会创建⼀个线程去执⾏任务，
 * 当线程池中的线程数⽬达到corePoolSize后，就会把到达的任务放到缓存队列当中；
 * 当队列满了，就继续创建线程，当线程数量⼤于等于maxPoolSize后，开始使⽤拒绝策略拒绝
 */
    /**
     * 核⼼线程数（默认线程数）
     */
    private final int corePoolSize = 20;
    /**
     * 最⼤线程数
     */

    private static final int maxPoolSize = 100;
    /**
     * 允许线程空闲时间（单位：默认为秒）
     */

    private static final int keepAliveTime = 10;
    /**
     * 缓冲队列⼤⼩
     */

    private static final int queueCapacity = 200;
    /**
     * 线程池名前缀
     */
    private static final String threadNamePrefix = "Async-Service-";

    //@Bean("taskExecutor") // bean的名称，默认为⾸字⺟⼩写的⽅法名
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNamePrefix);
        // 线程池对拒绝任务的处理策略
        // CallerRunsPolicy：由调⽤线程（提交任务的线程）处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }

}
